package com.github.baichuan.gb32960.codec;

import com.github.baichuan.gb32960.utils.ByteBufHelper;
import com.github.baichuan.iot.protocol.pdu.Decoder;
import io.netty.buffer.ByteBuf;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 燃料电池
 */
public class FuelCell implements Decoder {
    @Override
    public List<Map<String, Object>> decode(ByteBuf buf) {
        Map<String, Object> data = new TreeMap<>();

        // 电池电压
        ByteBufHelper.readUnsignedShort(buf).ifPresent(value -> {
            data.put("voltage", BigDecimal.valueOf(value * 0.1).setScale(1, RoundingMode.HALF_UP));
        });

        // 电池电流
        ByteBufHelper.readUnsignedShort(buf).ifPresent(value -> {
            data.put("current", BigDecimal.valueOf(value * 0.1).setScale(1, RoundingMode.HALF_UP));
        });

        // 燃料消耗率
        ByteBufHelper.readUnsignedShort(buf).ifPresent(value -> {
            data.put("fuelConsumption", BigDecimal.valueOf(value * 0.01).setScale(2, RoundingMode.HALF_UP));
        });

        // 温度探针总数
        ByteBufHelper.readUnsignedShort(buf).ifPresent(value -> {
            data.put("probe", value);

            int[] temperature = new int[value];
            data.put("temperature", temperature);
            // 探针温度
            for(int i = 0; i < value; i++){
                temperature[i] = buf.readUnsignedByte() - 40;
            }
        });

        // 氢系统中最高温度
        ByteBufHelper.readUnsignedShort(buf).ifPresent(value -> {
            data.put("maxTemp", BigDecimal.valueOf(value * 0.1 - 40).setScale(1, RoundingMode.HALF_UP));
        });

        // 氢系统中最高温度探针代号
        ByteBufHelper.readUnsignedByte(buf).ifPresent(value -> {
            data.put("maxTempProbe", value);
        });

        // 氢气最高浓度
        ByteBufHelper.readUnsignedShort(buf).ifPresent(value -> {
            data.put("maxConcentration", value);
        });

        // 氢气最高浓度传感器代号
        ByteBufHelper.readUnsignedByte(buf).ifPresent(value -> {
            data.put("maxConcentrationSensor", value);
        });

        // 氢气最高压力
        ByteBufHelper.readUnsignedShort(buf).ifPresent(value -> {
            data.put("maxPressure", value);
        });

        // 氢气最高压力传感器代号
        ByteBufHelper.readUnsignedByte(buf).ifPresent(value -> {
            data.put("maxPressureSensor", value);
        });

        // 高压DC/DC状态
        data.put("dcdc", buf.readUnsignedByte());

        return Arrays.asList(data);
    }
}
